package com.bestvike.stone.spring.boot;

import com.bestvike.stone.core.lang.StringUtils;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.stereotype.Component;

/**
 * Created by 许崇雷 on 2017-11-22.
 */
@CommonsLog
@Component
public final class ApplicationUtils {
    private static final ApplicationProperties EMPTY_PROPERTIES = new ApplicationProperties();
    private static ApplicationTemplate applicationTemplate;
    private static ApplicationProperties applicationProperties;

    static {
        EMPTY_PROPERTIES.setName(StringUtils.EMPTY);
        EMPTY_PROPERTIES.setDescription(StringUtils.EMPTY);
        EMPTY_PROPERTIES.setVersion(StringUtils.EMPTY);
    }

    ApplicationUtils(ApplicationTemplate applicationTemplateInstance) {
        applicationTemplate = applicationTemplateInstance;
        applicationProperties = applicationTemplateInstance.getProperties();
        log.info(String.format("Application name: %s, description: %s, version: %s", applicationProperties.getName(), applicationProperties.getDescription(), applicationProperties.getVersion()));
    }

    public static ApplicationProperties getProperties() {
        return applicationProperties == null ? EMPTY_PROPERTIES : applicationProperties;
    }

    public static Object getBean(String name) {
        try {
            return applicationTemplate == null ? null : applicationTemplate.getBean(name);
        } catch (Exception e) {
            return null;
        }
    }

    public static <T> T getBean(Class<T> clazz) {
        try {
            return applicationTemplate == null ? null : applicationTemplate.getBean(clazz);
        } catch (Exception e) {
            return null;
        }
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        try {
            return applicationTemplate == null ? null : applicationTemplate.getBean(name, clazz);
        } catch (Exception e) {
            return null;
        }
    }
}
